﻿using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using WindGoes6.Helper;
using WindGoes6.Security;

namespace WindGoes6.Sys
{
	/// <summary>
	/// 通过一系列算法，实现对软件的注册检查、注册码生成和注册功能。
	/// </summary>
	public class AppRegister
	{ 
		/// <summary>
		/// 注册的名称。
		/// </summary>
		public string Name { get; private set; } = "noname";

		/// <summary>
		/// 生成本注册文件的日期。
		/// </summary>
		public string MacAddress { get; private set; } = HardwareHelper.GetMacAddress();

		/// <summary>
		/// 是否已经注册。
		/// </summary>
		public bool Registed { get; private set; } = false;

		/// <summary>
		/// 文件的生成日期。
		/// </summary>
		public DateTime GeneratedDate { get; private set; } = DateTime.Now;

		/// <summary>
		/// 注册日期，默认为 2000/01/01 表示未注册。
		/// </summary>
		public DateTime RegistedDate { get; set; } = new DateTime(2000, 1, 1);


		public AppRegister()
		{

		}

		string seperator = "|[] []|";

		/// <summary>
		/// 生成注册文件。
		/// </summary>
		/// <param name="keyfile"></param>
		/// <returns></returns>
		public void MakeUnregistedKey(string keyfile = "unregisted.key")
		{
			File.WriteAllText("unregisted.key", DESCrypto.Encrypt(this.ToString()));
		}

		/// <summary>
		/// 输出字符串。
		/// </summary>
		/// <returns></returns>
		public override string ToString()
		{
			string[] data = new string[5];
			data[0] = Name;
			data[1] = MacAddress;
			data[2] = Registed ? "" : "";
			data[3] = GeneratedDate.ToShortDateString();
			data[4] = RegistedDate.ToShortDateString();
			return string.Join(seperator, data);
		}

		public static void RegisterKey(string infile, string outfile)
		{
			try
			{
				string originalText = DESCrypto.Decrypt(File.ReadAllText(infile)).Replace("UN", "RE");
				File.WriteAllText(outfile, DESCrypto.Encrypt(originalText));
			}
			catch (Exception exception)
			{
				Console.WriteLine(exception.Message);
			}
		}

	}
}
